package com.elong.android.specialhouse.utils;

import android.text.TextUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class DateTimeUtils {

    public static final String TAG = "DateTimeUtils";

    public static final int DATETIME_FIELD_REFERSH = 20; // 刷新时间(分钟)
    //
    public static final long ONE_SECOND = 1000L;
    public static final long ONE_MINUTE = ONE_SECOND * 60L;
    public static final long ONE_HOUR = ONE_MINUTE * 60L;
    public static final long ONE_DAY = ONE_HOUR * 24L;
    // 下面的pattern在print和parse时都可以使用
    public static final String MM_Yue_dd_Ri = "MM月dd日";
    public static final String yyyyMMdd = "yyyyMMdd";
    public static final String yyyy_MM_dd = "yyyy-MM-dd";
    public static final String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
    public static final String yyyy_MM_dd_HH_mm = "yyyy-MM-dd HH:mm";
    public static final String yyyyMMddHHmmss = "yyyyMMddHHmmss";
    public static final String yyyy_Nian_MM_Yue_dd_Ri = "yyyy年MM月dd日";
    public static final String MM_yy = "MM/yy";
    // 下面的pattern是print时用，parse时不应使用（只有时间，没有日期）
    public static final String HH_mm_ss = "HH:mm:ss";
    private static final String[] PATTERNS = {yyyy_MM_dd, yyyy_MM_dd_HH_mm_ss, yyyy_MM_dd_HH_mm, yyyyMMdd};

    public static final int DATETIME_FIELD_DATE = 0; // 日期 年月日
    public static final int DATETIME_FIELD_DATEWITHOUTYEAR = DATETIME_FIELD_DATE + 1; // 日期
    // 月日
    public static final int DATETIME_FIELD_YEAR = DATETIME_FIELD_DATEWITHOUTYEAR + 1; // 日期
    // 年
    public static final int DATETIME_FIELD_MONTH = DATETIME_FIELD_YEAR + 1; // 日期
    // 月
    public static final int DATETIME_FIELD_DAYOFMONTH = DATETIME_FIELD_MONTH + 1; // 日期
    // 日
    public static final int DATETIME_FIELD_TIME = DATETIME_FIELD_DAYOFMONTH + 1; // 时间
    // 时分秒
    public static final int DATETIME_FIELD_TIMEWITHOUTSECOND = DATETIME_FIELD_TIME + 1; // 时间
    // 时分
    public static final int DATETIME_FIELD_HOUROFDAY = DATETIME_FIELD_TIMEWITHOUTSECOND + 1; // 时间
    // 时
    public static final int DATETIME_FIELD_MINUTE = DATETIME_FIELD_HOUROFDAY + 1; // 时间
    // 分
    public static final int DATETIME_FIELD_SECOND = DATETIME_FIELD_MINUTE + 1; // 时间
    // 妙
    public static final int DATETIME_FIELD_DATETIMEWITHOUTSECOND = DATETIME_FIELD_SECOND + 1; // 日期时间
    // 年月日时分
    public static final int DATETIME_FIELD_DATEWITHOUTDAY = DATETIME_FIELD_DATETIMEWITHOUTSECOND + 1; // 日期
    // 年月
    public static final int DATETIME_FIELD_YEAR_SHORT = DATETIME_FIELD_DATEWITHOUTDAY + 1; // 日期
    // 年（如
    // 2001
    // ->
    // 01）

    public static void cleanCalendarTime(Calendar c) {
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    }

    public static int getBirthIntervalDays(Calendar d1, Calendar d2) {
        if (d1 == null || d2 == null) {
            throw new IllegalArgumentException();
        }
        return (int) (Math.abs(d2.getTimeInMillis() - d1.getTimeInMillis() + ONE_HOUR) / ONE_DAY);
    }

    /**
     * 获得指定日期表示格式转换成Calendar的格式
     *
     * @param src
     * @param fallback 若无法转换，返回一个默认值
     * @return
     */
    public static <T> Calendar getCalendar(T src, Calendar fallback) {
        if (src != null) {
            try {
                return getCalendar(src);
            } catch (Exception e) {
            }
        }
        fallback.setLenient(false);
        return fallback;
    }

    /**
     * 获得日期类型
     *
     * @param src 任何可以表示时间的类型，目前支持Calendar,Date,long,String
     * @return Calendar类型表示的时间
     * @throws IllegalArgumentException
     */
    public static <T> Calendar getCalendar(T src) {
        Calendar calendar = CalendarUtils.getCalendarInstance();
        calendar.setLenient(false);
        if (src == null) {
            return null;
        } else if (src instanceof Calendar) {
            calendar.setTimeInMillis(((Calendar) src).getTimeInMillis());
        } else if (src instanceof Date) {
            calendar.setTime((Date) src);
        } else if (src instanceof Long) {
            calendar.setTimeInMillis((Long) src);
        } else if (src instanceof String) {
            String nSrc = (String) src;
            try {
                // 直接匹配的时候不能匹配到月份或日期不是2位数的情况
                if (Pattern.compile("\\d{4}年\\d{1,2}月\\d{1,2}日").matcher(nSrc).find()) {
                    nSrc = fixDateString(nSrc);
                    return getCalendarByPattern(nSrc, yyyy_MM_dd);
                }
                return getCalendarByPatterns(nSrc, PATTERNS);
            } catch (Exception e) {
                try {
                    calendar.setTimeInMillis(Long.valueOf(nSrc));
                } catch (NumberFormatException e1) {
                    throw new IllegalArgumentException(e1);
                }
            }
        } else {
            throw new IllegalArgumentException();
        }
        return calendar;
    }

    /**
     * YYYY年MM月DD日 --> YYYY-MM-DD
     */
    private static String fixDateString(String date) {
        if (TextUtils.isEmpty(date)) {
            return date;
        }

        String[] dateArray = date.split("[年月日]");
        if (dateArray.length == 1) {
            dateArray = date.split("-");
        }
        for (int i = 0; i < 3; i++) {
            if (dateArray[i].length() == 1) {
                dateArray[i] = "0" + dateArray[i];
            }
        }
        return dateArray[0] + "-" + dateArray[1] + "-" + dateArray[2];
    }

    // calendar --> YYYY-MM-DD HH:MM:SS
    public static String formatCalendarToDateTimeString(Calendar aTime) {
        String date = String.valueOf(aTime.get(Calendar.YEAR)) + "-";
        if (aTime.get(Calendar.MONTH) + 1 < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.MONTH) + 1) + "-";
        } else {
            date += String.valueOf(aTime.get(Calendar.MONTH) + 1) + "-";
        }
        if (aTime.get(Calendar.DAY_OF_MONTH) < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.DAY_OF_MONTH));
        } else {
            date += String.valueOf(aTime.get(Calendar.DAY_OF_MONTH));
        }
        date += " ";
        if (aTime.get(Calendar.HOUR_OF_DAY) < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.HOUR_OF_DAY)) + ":";
        } else {
            date += String.valueOf(aTime.get(Calendar.HOUR_OF_DAY)) + ":";
        }
        if (aTime.get(Calendar.MINUTE) < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.MINUTE)) + ":";
        } else {
            date += String.valueOf(aTime.get(Calendar.MINUTE)) + ":";
        }
        if (aTime.get(Calendar.SECOND) < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.SECOND));
        } else {
            date += String.valueOf(aTime.get(Calendar.SECOND));
        }

        return date;
    }

    /**
     * @param @param  aTime
     * @param @return
     * @return String
     * @throws
     * @Title: formatCalendarToDateString
     * @Description: 格式化Calendar为日期字符串:yyyy-MM-dd
     */
    public static String formatCalendarToDateString(Calendar aTime) {
        String date = String.valueOf(aTime.get(Calendar.YEAR)) + "-";
        if (aTime.get(Calendar.MONTH) + 1 < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.MONTH) + 1) + "-";
        } else {
            date += String.valueOf(aTime.get(Calendar.MONTH) + 1) + "-";
        }
        if (aTime.get(Calendar.DAY_OF_MONTH) < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.DAY_OF_MONTH));
        } else {
            date += String.valueOf(aTime.get(Calendar.DAY_OF_MONTH));
        }

        return date;
    }

    /**
     * @param @param  aTime
     * @param @return
     * @return String
     * @throws
     * @Title: formatCalendarToDateString
     * @Description: 格式化Calendar为日期字符串:yyyy*MM*dd (*代表tag)
     */
    public static String formatCalendarToDateString(Calendar aTime, String tag) {
        String date = String.valueOf(aTime.get(Calendar.YEAR)) + tag;
        if (aTime.get(Calendar.MONTH) + 1 < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.MONTH) + 1) + tag;
        } else {
            date += String.valueOf(aTime.get(Calendar.MONTH) + 1) + tag;
        }
        if (aTime.get(Calendar.DAY_OF_MONTH) < 10) {
            date += "0" + String.valueOf(aTime.get(Calendar.DAY_OF_MONTH));
        } else {
            date += String.valueOf(aTime.get(Calendar.DAY_OF_MONTH));
        }

        return date;
    }

    // Calendar --> YYYY-MM-DD HH:MM:SS 可配置
    public static String getFieldStringFromCalendar(Calendar aCalendar, int field) {
        String ret = "";
        switch (field) {
            case DATETIME_FIELD_DATE:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(0, 10);
                break;
            case DATETIME_FIELD_DATEWITHOUTDAY:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(0, 7);
                break;
            case DATETIME_FIELD_DATEWITHOUTYEAR:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(5, 10);
                break;
            case DATETIME_FIELD_YEAR:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(0, 4);
                break;
            case DATETIME_FIELD_MONTH:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(5, 7);
                break;
            case DATETIME_FIELD_DAYOFMONTH:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(8, 10);
                break;
            case DATETIME_FIELD_TIME:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(11, 19);
                break;
            case DATETIME_FIELD_TIMEWITHOUTSECOND:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(11, 16);
                break;
            case DATETIME_FIELD_HOUROFDAY:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(11, 13);
                break;
            case DATETIME_FIELD_MINUTE:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(14, 16);
                break;
            case DATETIME_FIELD_SECOND:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(17, 19);
                break;
            case DATETIME_FIELD_DATETIMEWITHOUTSECOND:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(0, 16);
                break;
            case DATETIME_FIELD_YEAR_SHORT:
                ret = formatCalendarToDateTimeString(aCalendar);
                ret = ret.substring(2, 4);
                break;
            default:
                break;
        }
        return ret;
    }

    /**
     * 匹配pattern获得时间，若无法解析抛出异常
     *
     * @param dateTimeStr
     * @param patternStr
     * @return
     * @throws IllegalArgumentException
     */
    public static Calendar getCalendarByPattern(String dateTimeStr, String patternStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(patternStr, Locale.US);
            sdf.setLenient(false);
            Date d = sdf.parse(dateTimeStr);
            Calendar c = CalendarUtils.getCalendarInstance();
            c.setLenient(false);
            c.setTimeInMillis(d.getTime());
            return c;
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 匹配pattern数组中的所有pattern解析时间格式，若没有可以解析的方式则抛出异常
     *
     * @param dateTimeStr
     * @param patternStr
     * @return
     * @throws IllegalArgumentException
     */
    public static Calendar getCalendarByPatterns(String dateTimeStr, String[] patternStr) {
        for (String string : patternStr) {
            try {
                return getCalendarByPattern(dateTimeStr, string);
            } catch (Exception e) {
//				LogWriter.logException(TAG, "", e);
            }
        }

        throw new IllegalArgumentException();
    }

    /**
     * 是否有服务器时间
     */
    public static boolean hasServerTime;
    /**
     * 本地时间和服务器时间的间隔 time server local gap millis
     */
    public static long tslgapm;
    /**
     * 本地时间和服务器时间的间隔 time server string
     */
    public static String tss;

    /**
     * 获取与服务器时间矫正过的当前时间
     */
    public static Calendar getCurrentDateTime() {
        Calendar now = CalendarUtils.getCalendarInstance();
        now.setLenient(false);
        if (hasServerTime) {
            now.setTimeInMillis(now.getTimeInMillis() + tslgapm);
        }
        return now;
    }

    /**
     * 获取与服务器时间矫正过的当前时间 -国际酒店，可选日期向前推一天
     */
    public static Calendar getCurrentDateTimeForGloal() {
        Calendar now = CalendarUtils.getCalendarInstance();
        now.add(Calendar.DAY_OF_MONTH, -1);
        now.setLenient(false);
        if (hasServerTime) {
            now.setTimeInMillis(now.getTimeInMillis() + tslgapm);
        }
        return now;
    }

    /**
     * 获取与服务器时间矫正过的当前时间 -凌晨预订，可选日期向前推6小时
     */
    public static Calendar getCurrentDateTimeForMorning() {
        Calendar now = CalendarUtils.getCalendarInstance();
        now.add(Calendar.HOUR_OF_DAY, -6);
        now.setLenient(false);
        if (hasServerTime) {
            now.setTimeInMillis(now.getTimeInMillis() + tslgapm);
        }
        return now;
    }

    public static Calendar getCurrentServerDate() {
        return getCalendar(tss);
    }

    /**
     * 获得基准日期增加间隔天
     */
    public static Calendar getDateAdd(Calendar start, int interval) {
        if (start == null) {
            return null;
        }
        Calendar c = (Calendar) start.clone();
        c.add(Calendar.DATE, interval);
        return c;
    }

    /**
     * 获得时间间隔
     *
     * @param from
     * @param to
     * @param unit 时间间隔单位{@link DateTimeUtils#ONE_SECOND},
     *             {@link DateTimeUtils#ONE_MINUTE},
     *             {@link DateTimeUtils#ONE_HOUR}, {@link DateTimeUtils#ONE_DAY}
     * @return
     */
    public static long getIntervalTimes(Calendar from, Calendar to, long unit) {
        if (from == null || to == null) {
            throw new IllegalArgumentException();
        }
        return Math.abs(from.getTimeInMillis() - to.getTimeInMillis()) / unit;
    }

    /**
     * 获得日期间隔 忽略小时
     *
     * @param from
     * @param to
     * @return
     */
    public static long getIntervalTimes(Calendar from, Calendar to) {
        Calendar f = ((Calendar) from.clone());
        Calendar t = ((Calendar) to.clone());
        if (from == null || to == null) {
            throw new IllegalArgumentException();
        }
        cleanCalendarTime(f);
        cleanCalendarTime(t);
        return getIntervalTimes(from, to, ONE_DAY);
    }

    public static int getIntervalDays(String startdate, String enddate, String pattern) {
        int betweenDays = 0;
        if (startdate == null || enddate == null) {
            return betweenDays;
        }

        Calendar d1 = getCalendarByPattern(startdate, pattern);
        Calendar d2 = getCalendarByPattern(enddate, pattern);

        return getIntervalDays(d1, d2);
    }

    public static int getIntervalDays(Calendar from, Calendar to) {
        long dayMillis = 24 * 60 * 60 * 1000;
        int betweenDays = 0;
        Calendar c1 = CalendarUtils.getCalendarInstance();
        c1.set(from.get(Calendar.YEAR), from.get(Calendar.MONTH), from.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        c1.set(Calendar.MILLISECOND, 0);
        Calendar c2 = CalendarUtils.getCalendarInstance();
        c2.set(to.get(Calendar.YEAR), to.get(Calendar.MONTH), to.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        c2.set(Calendar.MILLISECOND, 0);
        long a = c1.getTimeInMillis();
        long b = c2.getTimeInMillis();
        long bt = Math.abs(a - b);
        betweenDays = (int) (bt / dayMillis);
        return betweenDays;
    }

    // 上车时间08:30,用时:1天23小时30分
    public static String getIntervalDaysForRailway(String startdate, String totalTime) {
        if (startdate == null || totalTime == null) {
            return "";
        }
        String[] startdates = startdate.split(":");
        Calendar startCalendar = CalendarUtils.getCalendarInstance();
        startCalendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startdates[0]));
        startCalendar.set(Calendar.MINUTE, Integer.parseInt(startdates[0]));

        Calendar endCalendar = (Calendar) startCalendar.clone();
        String patternStr = "((\\d+)天)?((\\d+)小时)?((\\d+)分)?";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(totalTime);
        if (matcher.find()) {
            String day = matcher.group(2);
            if (!TextUtils.isEmpty(day)) {
                endCalendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
            }
            String hour = matcher.group(4);
            if (!TextUtils.isEmpty(hour)) {
                endCalendar.add(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
            }
            String minute = matcher.group(6);
            if (!TextUtils.isEmpty(minute)) {
                endCalendar.add(Calendar.MINUTE, Integer.parseInt(minute));
            }
            long days = getIntervalDays(startCalendar, endCalendar);
            if (days == 1) {
                return "(次日)";
            } else if (days == 2) {
                return "(第三日)";
            }
        }
        return "";
    }

    /**
     * calendar --> 周一～七
     */
    public static String getWeekDayFromCalendar(Calendar cal) {
        if (cal == null) {
            throw new IllegalArgumentException();
        }
        switch (cal.get(Calendar.DAY_OF_WEEK)) {
            case 1:
                return "周日";
            case 2:
                return "周一";
            case 3:
                return "周二";
            case 4:
                return "周三";
            case 5:
                return "周四";
            case 6:
                return "周五";
            case 7:
                return "周六";
        }
        throw new NullPointerException();
    }

    /**
     * calendar --> 星期天～星期六
     */
    public static String getWeekDayFromCalendar1(Calendar cal) {
        if (cal == null) {
            throw new IllegalArgumentException();
        }
        switch (cal.get(Calendar.DAY_OF_WEEK)) {
            case 1:
                return "星期天";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
        }
        throw new IllegalArgumentException();
    }

    /**
     * weeekDay
     *
     * @param currSelectedDate
     * @return
     */
    public static String getShowWeekDay(Calendar currSelectedDate, boolean isGlobalDate) {

        String weekDay = DateTimeUtils.getWeekDayFromCalendar(currSelectedDate);
        if (isGlobalDate) {
            return weekDay;
        }
        if (DateTimeUtils.compareCalendar(currSelectedDate, CalendarUtils.getCalendarInstance()) == 0) {
            weekDay = "今天";
        } else {
            Calendar tmp = CalendarUtils.getCalendarInstance();
            tmp.add(Calendar.DAY_OF_MONTH, 1);
            if (DateTimeUtils.compareCalendar(currSelectedDate, tmp) == 0) {
                weekDay = "明天";
            }
        }
        return weekDay;
    }

    /**
     * getShowDayNormal
     *
     * @param currSelectedDate
     * @return "今天","明天","后天"
     */
    public static String getShowDayNormal(Calendar currSelectedDate) {

        String weekDay = "";
        Calendar tmp = CalendarUtils.getCalendarInstance();
        if (DateTimeUtils.compareCalendar(currSelectedDate, tmp) == 0) {
            weekDay = "今天";
        } else {
            tmp.add(Calendar.DAY_OF_MONTH, 1);
            if (DateTimeUtils.compareCalendar(currSelectedDate, tmp) == 0) {
                weekDay = "明天";
            } else {
                tmp.add(Calendar.DAY_OF_MONTH, 1);
                if (DateTimeUtils.compareCalendar(currSelectedDate, tmp) == 0) {
                    weekDay = "后天";
                }
            }
        }
        return weekDay;
    }

    /*
     * 获取酒店搜索页面对齐时间
     */
    public static String getAlignedTime(int time) {
        String timeStr;
        if (time < 10) {
            timeStr = "0" + time;
        } else {
            timeStr = String.valueOf(time);
        }

        return timeStr;
    }

    /**
     * 判断是否是闰年
     *
     * @param date (2009-10-13 || 2009年10月13日 || 2009)
     * @return true 是 false 不是
     * @author jie.cui
     */
    public static boolean isLeapyear(String date) {
        if (date.contains("-") || date.contains("年") && date.contains("月")) {
            String year = date.substring(0, 3);
            int yeatInt = Integer.parseInt(year);
            if (yeatInt % 100 == 0 && yeatInt % 400 == 0 || yeatInt % 100 != 0 && yeatInt % 4 == 0) {
                return true;
            }
        }
        return false;
    }

    // 是否到刷新时间
    public static boolean isRefersh(long beforeTime) {
        return isRefersh(DATETIME_FIELD_REFERSH * 1000 * 60, beforeTime);
    }

    // 是否到刷新时间
    public static boolean isRefersh(long gap, long beforeTime) {
        return new Date().getTime() - beforeTime >= gap;
    }

    public static String printCalendarByPattern(Calendar c, String patternStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(patternStr, Locale.US);
        sdf.setLenient(false);
        return sdf.format(new Date(c.getTimeInMillis()));
    }

    // 产生节日
    public static HashMap<Calendar, String> genHolidays() {
        HashMap<Calendar, String> holidays = new HashMap<Calendar, String>();
        // 产品提需求去掉非放假节日
        Calendar c = getCalendar("2015-01-01");
        holidays.put(c, "元旦");
        // c = getCalendar("2015-02-14");
        // holidays.put(c, "情人节");
        // c = getCalendar("2015-02-18");
        // holidays.put(c, "除夕");
        c = getCalendar("2015-02-19");
        holidays.put(c, "春节");
        c = getCalendar("2015-04-05");
        holidays.put(c, "清明");
        c = getCalendar("2015-05-01");
        holidays.put(c, "劳动节");
        // c = getCalendar("2015-05-10");
        // holidays.put(c, "母亲节");
        // c = getCalendar("2015-06-01");
        // holidays.put(c, "儿童节");
        c = getCalendar("2015-06-20");
        holidays.put(c, "端午");
        // c = getCalendar("2015-06-21");
        // holidays.put(c, "父亲节");
        c = getCalendar("2015-09-27");
        holidays.put(c, "中秋");
        // c = getCalendar("2015-09-10");
        // holidays.put(c, "教师节");
        c = getCalendar("2015-10-01");
        holidays.put(c, "国庆节");
        // c = getCalendar("2015-12-25");
        // holidays.put(c, "圣诞节");
        c = getCalendar("2016-01-01");
        holidays.put(c, "元旦");
        // c = getCalendar("2016-02-07");
        // holidays.put(c, "除夕");
        c = getCalendar("2016-02-08");
        holidays.put(c, "春节");

        return holidays;
    }

    public static class WeekendHolidayBean {
        private Calendar key;
        private boolean isHoliday;

        public Calendar getKey() {
            return key;
        }

        public void setKey(Calendar key) {
            this.key = key;
        }

        public boolean isHoliday() {
            return isHoliday;
        }

        public void setHoliday(boolean isHoliday) {
            this.isHoliday = isHoliday;
        }
    }

    // 产生结假日节日有周未所有放假日期 by wmh
    public static List<WeekendHolidayBean> genWeekendHolidays() {
        ArrayList<WeekendHolidayBean> weekendHolidays = new ArrayList<WeekendHolidayBean>();

        String strWeekendholdays = "2015-01-01|2015-01-02|2015-01-03|";
        strWeekendholdays += "2015-02-18|2015-02-19|2015-02-20|2015-02-21|2015-02-22|2015-02-23|2015-02-24|";
        strWeekendholdays += "2015-04-04|2015-04-05|2015-04-06|";
        strWeekendholdays += "2015-05-01|2015-05-02|2015-05-03|";
        strWeekendholdays += "2015-06-20|2015-06-21|2015-06-22|";
        strWeekendholdays += "2015-09-03|2015-09-04|2015-09-05|2015-09-26|2015-09-27|";
        strWeekendholdays += "2015-10-01|2015-10-02|2015-10-03|2015-10-04|2015-10-05|2015-10-06|2015-10-07|";
        strWeekendholdays += "2016-01-01|2016-01-02|2016-01-03|";
        strWeekendholdays += "2016-02-07|2016-02-08|2016-02-09|2016-02-10|2016-02-11|2016-02-12|2016-02-13";
        String[] tempArrayDays = strWeekendholdays.split("\\|");
        Calendar c;
        for (int i = 0; i < tempArrayDays.length; i++) {
            if (tempArrayDays[i] != null && tempArrayDays[i].length() > 0) {
                c = getCalendar(tempArrayDays[i]);
                WeekendHolidayBean object = new WeekendHolidayBean();
                object.setKey(c);
                object.setHoliday(true);
                weekendHolidays.add(object);
            }
        }
        String strworkdays = "2015-01-04|2015-02-15|2015-02-28|2015-09-06|2015-10-10|2016-02-06|2016-02-14";
        tempArrayDays = strworkdays.split("\\|");
        for (int i = 0; i < tempArrayDays.length; i++) {
            if (tempArrayDays[i] != null && tempArrayDays[i].length() > 0) {
                c = getCalendar(tempArrayDays[i]);
                WeekendHolidayBean object = new WeekendHolidayBean();
                object.setKey(c);
                object.setHoliday(false);
                weekendHolidays.add(object);
            }
        }
        return weekendHolidays;
    }

    /**
     * @param @return
     * @return Map<Calendar,Boolean> <日期,是否需要休息> true休息；false上班。
     * @throws
     * @Title: genWeekendHolidaysForFlight
     * @Description: 周六周日需要正常上班，或者非周六周日休息
     */
    public static Map<Calendar, Boolean> genWeekendHolidaysForFlight() {
        Map<Calendar, Boolean> weekendHolidays = new HashMap<Calendar, Boolean>();
        // 本应该是工作日的，因为节假日调班需要休息的日期
        String weekend = "2015-01-01|2015-01-02|2015-01-03|";
        weekend += "2015-02-18|2015-02-19|2015-02-20|2015-02-21|2015-02-22|2015-02-23|2015-02-24|";
        weekend += "2015-04-04|2015-04-05|2015-04-06|";
        weekend += "2015-05-01|2015-05-02|2015-05-03|";
        weekend += "2015-06-20|2015-06-21|2015-06-22|";
        weekend += "2015-09-26|2015-09-27|";
        weekend += "2015-10-01|2015-10-02|2015-10-03|2015-10-04|2015-10-05|2015-10-06|2015-10-07";
        String[] tempArrayDays = weekend.split("\\|");
        for (String day : tempArrayDays) {
            if (day != null && day.length() > 0) {
                Calendar c = getCalendar(day);
                weekendHolidays.put(c, true);
            }
        }
        // 本应该周六周日休息，但需要上班的日期
        String work = "2015-01-04|2015-02-15|2015-02-28|2015-10-10";
        tempArrayDays = work.split("\\|");
        for (String day : tempArrayDays) {
            if (day != null && day.length() > 0) {
                Calendar c = getCalendar(day);
                weekendHolidays.put(c, false);
            }
        }

        return weekendHolidays;
    }

    /**
     * c1 < c2 = -1 ; c1 > c2 = 1 ; c1 == c2 = 0
     */
    public static int compareCalendar(Calendar c1, Calendar c2) {
        if (c1.get(Calendar.YEAR) > c2.get(Calendar.YEAR)) {
            return 1;
        } else if (c1.get(Calendar.YEAR) < c2.get(Calendar.YEAR)) {
            return -1;
        } else {
            if (c1.get(Calendar.MONTH) > c2.get(Calendar.MONTH)) {
                return 1;
            } else if (c1.get(Calendar.MONTH) < c2.get(Calendar.MONTH)) {
                return -1;
            } else {
                if (c1.get(Calendar.DAY_OF_MONTH) > c2.get(Calendar.DAY_OF_MONTH)) {
                    return 1;
                } else if (c1.get(Calendar.DAY_OF_MONTH) < c2.get(Calendar.DAY_OF_MONTH)) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    }

    /**
     * 计算两个日期的时间间隔
     *
     * @param sDate 开始时间
     * @param eDate 结束时间
     * @param type  间隔类型
     *              ("Y/y"--年 "M/m"--月 "D/d"--日)
     * @return interval时间间隔
     */
    public static int calInterval(Date sDate, Date eDate, String type) {
        // 时间间隔，初始为0
        int interval = 0;

		/* 比较两个日期的大小，如果开始日期更大，则交换两个日期 */
        // 标志两个日期是否交换过
        boolean reversed = false;
        if (compareDate(sDate, eDate) > 0) {
            Date dTest = sDate;
            sDate = eDate;
            eDate = dTest;
            // 修改交换标志
            reversed = true;
        }

		/* 将两个日期赋给日历实例，并获取年、月、日相关字段值 */
        Calendar sCalendar = Calendar.getInstance();
        sCalendar.setTime(sDate);
        int sYears = sCalendar.get(Calendar.YEAR);
        int sMonths = sCalendar.get(Calendar.MONTH);
        int sDays = sCalendar.get(Calendar.DAY_OF_YEAR);

        Calendar eCalendar = Calendar.getInstance();
        eCalendar.setTime(eDate);
        int eYears = eCalendar.get(Calendar.YEAR);
        int eMonths = eCalendar.get(Calendar.MONTH);
        int eDays = eCalendar.get(Calendar.DAY_OF_YEAR);

        // 年
        if (cTrim(type).equals("Y") || cTrim(type).equals("y")) {
            interval = eYears - sYears;
            if (eMonths < sMonths) {
                --interval;
            }
        }
        // 月
        else if (cTrim(type).equals("M") || cTrim(type).equals("m")) {
            interval = 12 * (eYears - sYears);
            interval += (eMonths - sMonths);
        }
        // 日
        else if (cTrim(type).equals("D") || cTrim(type).equals("d")) {
            interval = 365 * (eYears - sYears);
            interval += (eDays - sDays);
            // 除去闰年天数
            while (sYears < eYears) {
                if (isLeapYear(sYears)) {
                    --interval;
                }
                ++sYears;
            }
        }
        // 如果开始日期更大，则返回负值
        if (reversed) {
            interval = -interval;
        }
        // 返回计算结果
        return interval;
    }

    /**
     * 比较两个Date类型的日期大小
     *
     * @param sDate 开始时间
     * @param eDate 结束时间
     * @return result返回结果(0--相同 1--前者大 2--后者大)
     */
    private static int compareDate(Date sDate, Date eDate) {
        int result = 0;
        // 将开始时间赋给日历实例
        Calendar sC = Calendar.getInstance();
        sC.setTime(sDate);
        // 将结束时间赋给日历实例
        Calendar eC = Calendar.getInstance();
        eC.setTime(eDate);
        // 比较
        result = sC.compareTo(eC);
        // 返回结果
        return result;
    }

    /**
     * 字符串去除两头空格，如果为空，则返回""，如果不空，则返回该字符串去掉前后空格
     *
     * @param tStr 输入字符串
     * @return 如果为空，则返回""，如果不空，则返回该字符串去掉前后空格
     */
    private static String cTrim(String tStr) {
        String ttStr = "";
        if (tStr == null) {
        } else {
            ttStr = tStr.trim();
        }
        return ttStr;
    }

    /**
     * 判定某个年份是否是闰年
     *
     * @param year 待判定的年份
     * @return 判定结果
     */
    private static boolean isLeapYear(int year) {
        return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));
    }

    /**
     * 通过输入的Calendar,返回指定格式的日期
     *
     * @param c
     * @return XX/XX
     */
    public static String getFormatedTime(Calendar c) {
        if (null == c) {
            return "";
        }
        SimpleDateFormat df = new SimpleDateFormat("MM/dd");
        String result = df.format(c.getTime());
        return result;
    }

    /**
     * 通过输入的Calendar,返回指定格式的日期
     *
     * @param c
     * @return MM月dd日
     */
    public static String getMonthAndDay(Calendar c) {
        if (null == c) {
            return "";
        }
        SimpleDateFormat df = new SimpleDateFormat("MM月dd日");
        String result = df.format(c.getTime());
        return result;
    }

    /**
     * 转换日期为*月*日
     *
     * @param str
     * @return
     */
    public static String monthAndDay(String str) {
        if (str.length() < 19) {
            return "";
        }
        Long date = Long.parseLong(str.substring(6, 19));
        Date dt = new Date(date);
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String newDate = sdf.format(dt);
        return newDate;
    }

    /**
     * 转换日期为*月*日 周几
     *
     * @param str
     * @return
     */
    public static String monthDayAndWeek(String str) {
        if (str.length() < 19) {
            return "";
        }
        Long date = Long.parseLong(str.substring(6, 19));
        Date dt = new Date(date);
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String newDate = sdf.format(dt);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dt);
        return newDate + CalendarUtils.getWeek(calendar);
    }

    /**
     * 转换日期为*月*日 周几
     *
     * @param str
     * @return
     */
    public static String monthDayAndWeekAll(String str) {
        Long date = Long.parseLong(str);
        Date dt = new Date(date);
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String newDate = sdf.format(dt);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dt);
        return newDate + CalendarUtils.getWeek(calendar);
    }

    /**
     * 转换日期为小时分钟
     *
     * @param string
     * @return
     */
    public static String hourAndMinutes(String string) {
        if (string.length() < 19) {
            return "";
        }
        Long date = Long.parseLong(string.substring(6, 19));
        Date dt = new Date(date);
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String newDate = sdf.format(dt);
        return newDate;
    }

    /**
     * 转换日期为小时分钟
     *
     * @param string
     * @return
     */
    public static String hourAndMinutesAll(String string) {
        Long date = Long.parseLong(string);
        Date dt = new Date(date);
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String newDate = sdf.format(dt);
        return newDate;
    }

    /**
     * 计算两个日期的时间间隔
     *
     * @param sDate 开始时间
     * @param eDate 结束时间
     * @return interval时间间隔
     */
    public static String calIntervalDate(String sDate, String eDate) {
        if (sDate.length() < 19) {
            return "";
        }
        Long sDateLong = Long.parseLong(sDate.substring(6, 19));

        if (eDate.length() < 19) {
            return "";
        }
        Long eDateLong = Long.parseLong(eDate.substring(6, 19));
        if (eDateLong < sDateLong) {
            return "";
        }

        return "历时   " + ((eDateLong - sDateLong) / (1000 * 24 * 60 * 60)) + "天"
                + ((eDateLong - sDateLong) / (1000 * 60 * 60)) % 24 + "小时" + ((eDateLong - sDateLong) / (1000 * 60))
                % 60 + "分";
    }

    /**
     * 计算两个日期的时间间隔
     *
     * @param sDate 开始时间
     * @param eDate 结束时间
     * @return interval时间间隔
     */
    public static String calIntervalDateAll(String sDate, String eDate) {
        Long sDateLong = Long.parseLong(sDate);
        Long eDateLong = Long.parseLong(eDate);
        if (eDateLong < sDateLong) {
            return "";
        }

        return "历时   " + ((eDateLong - sDateLong) / (1000 * 24 * 60 * 60)) + "天"
                + ((eDateLong - sDateLong) / (1000 * 60 * 60)) % 24 + "小时" + ((eDateLong - sDateLong) / (1000 * 60))
                % 60 + "分";
    }

    /**
     * @param c
     * @param pattern 如“MM月dd日”
     * @return 由pattern定义的日期格式 如“MM月dd日”
     */
    public static String formatDateByPattern(Calendar c, String pattern) {
        Date date = c.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }


    /**
     * 把 yyyy-MM-dd类型的日期转成 M月d日 类型的
     *
     * @return M月dd日 类型的日期
     */
    public static String parseStringDate(String dateString) {
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            Date date = sdf1.parse(dateString);
            SimpleDateFormat sdf2 = new SimpleDateFormat("M月-d日", Locale.CHINA);
            return sdf2.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 修改日期格式，从yyyy-MM-dd的格式改为yyyy年MM月dd日
     * 当年的改为MM月dd日
     *
     * @param date
     * @return
     */
    public static String changeDateFormat(String date) {
        Date d = null;
        try {
            d = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            Calendar cal = Calendar.getInstance();
            Date currentTime = cal.getTime();//当前时间的上个月时间
            SimpleDateFormat sdf ;
            if (isDateInOneYear(d, currentTime)) {
                sdf = new SimpleDateFormat("MM月dd日");

            } else {
                sdf = new SimpleDateFormat("yyyy年MM月dd日");
            }
            return sdf.format(d);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 修改日期格式，从yyyy-MM-dd的格式改为yyyy年MM月dd日
     *
     * @param date
     * @return
     */
    public static String changeDateFormatContainsYear(String date) {
        Date d = null;
        try {
            d = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyy年MM月dd日");
            return sdf.format(d);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断日期是不是在同一年
     *
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isDateInOneYear(Date date1, Date date2) {
        Calendar c = Calendar.getInstance();
        c.setTime(date1);
        int month1 = c.get(Calendar.YEAR);
        c.setTime(date2);
        int month2 = c.get(Calendar.YEAR);
        return month1 == month2;
    }
    /**
     * 判断日期是不是在同一年
     *
     * @param date1
     * @param date2
     * @param format 字符串日期的格式
     * @return
     */
    public static boolean isDateInOneYear(String date1, String date2,String format) {
        Calendar c = Calendar.getInstance();
        c.setTime(getDateFromString(date1,format));
        int month1 = c.get(Calendar.YEAR);
        c.setTime(getDateFromString(date2,format));
        int month2 = c.get(Calendar.YEAR);
        return month1 == month2;
    }

    /**
     * 完成时间格式的指定
     * 显示为今天，昨天，6-10等处理
     *
     * @param time
     * @return
     */
    public static String getFormatTime(Date time) {
        Calendar c = Calendar.getInstance();
        Date today = c.getTime();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String todayStr = df.format(today);
        String timeStr = df.format(time);
        c.add(Calendar.DAY_OF_MONTH, -1);//昨天的日期
        Date yesterday = c.getTime();
        String yesterdayStr = df.format(yesterday);
        if (timeStr.equals(todayStr)) {
            return new SimpleDateFormat("HH:mm").format(time);
        } else if (timeStr.equals(yesterdayStr)) {
            return "昨天";
        } else if (isDateInOneYear(time, today)) {//是不是今年的日期
            return new SimpleDateFormat("MM-dd").format(time);
        }
        return timeStr;
    }

    public static Date getDateFromString(String data,String format) {
        Date date = null;
        DateFormat dateFormat = new SimpleDateFormat(format);
        try {
            date = dateFormat.parse(data);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String getDisplayTime(Date date) {
        DateFormat todayFormat = new SimpleDateFormat("HH:mm");
        DateFormat otherFormat = new SimpleDateFormat("MM-dd");
        long now = Calendar.getInstance().getTimeInMillis();
        long tag = date.getTime();
        long diff = now - tag;
        if (diff < 0) {
            return "";
        } else if (diff < 3 * 60 * 1000) { //3分钟以内显示"刚刚"
            return "刚刚";
        } else if (diff < 24 * 3600 * 1000) { //当天，则显示hh:mm
            return todayFormat.format(date);
        } else if (diff < 2 * 24 * 3600 * 1000) {//显示为"昨天"
            return "昨天";
        } else {//显示为MM:dd
            return otherFormat.format(date);
        }
    }

    /**
     * 修改日期格式，从oldPattern的格式改为newPattern
     *
     * @param date 需要转换的日期
     * @param oldPattern 转换前的模式
     * @param newPattern 转换后的模式
     * @return
     */
    public static String changeDateFormat(String date,String oldPattern,String newPattern) {
        Date d = null;
        try {
            d = new SimpleDateFormat(oldPattern).parse(date);
            SimpleDateFormat sdf =  new SimpleDateFormat(newPattern);
            return sdf.format(d);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
